package com.appspot.niehonglei.path;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 过虑classpath:path.xml配置的所有url,如果符合要求则跳转到相应
 * 的地址，如果不配置则返回继续执行
 * @author nehnre
 * 2010-3-12
 */
public class PathFilter extends HttpServlet implements Filter {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private FilterConfig filterConfig;
	
	private String separator = "_";

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain filterChain) {
		try {
			/** 解析地址 * */
			HttpServletRequest request = (HttpServletRequest) req;
			HttpServletResponse response = (HttpServletResponse) res;
			String basePath = request.getScheme() + "://"
					+ request.getServerName() + ":" + request.getServerPort()
					+ request.getContextPath();
			String urlPath = request.getServletPath();
			System.out.println(this.getClass().getName() + "：Line " + new Throwable().getStackTrace()[0].getLineNumber()+ "\t" + "urlPath" + "\t" + urlPath);
			String fileName = "default";
			// urlPath形成像/path1/path2/的样式
			fileName = urlPath.substring(urlPath.lastIndexOf("/") + 1);
			urlPath = urlPath.substring(0, urlPath.lastIndexOf("/") + 1);

			String encodePath = urlPath.replaceAll("/", separator);
			System.out.println(this.getClass().getName() + "：Line " + new Throwable().getStackTrace()[0].getLineNumber() + "\t" + "encodePath" + "\t" + encodePath);
			
			
			/** 解析xml * */
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			// 通过文档构建器工厂获取一个文档构建器
			DocumentBuilder db = dbf.newDocumentBuilder();
			// 通过文档通过文档构建器构建一个文档实例
			Document doc = db.parse(PathFilter.class.getResourceAsStream("/path.xml"));
			Node node = doc.getElementById(encodePath);
			if (node != null) {
				System.out.println(this.getClass().getName() + "：Line " + new Throwable().getStackTrace()[0].getLineNumber()+ "\t" + "encodePath" + "\t"  + encodePath);
				NodeList childNodes = node.getChildNodes();
				
				String forwardUrl = "";
				String defaultUrl = "";
				String anyUrl = "";
				boolean defaultAnonymous = true;
				boolean anyAnonymous = true;
				boolean anonymous = true;
				if(node.getAttributes().getNamedItem("anonymous")!=null){
					if("false".equals(node.getAttributes().getNamedItem("anonymous").getNodeValue())){
						anonymous = false;
						defaultAnonymous = false;
						anyAnonymous = false;
					}
				}
				for (int i = 0; i < childNodes.getLength(); i++) {
					Node childNode = childNodes.item(i);
					if (childNode.hasChildNodes()) {
						if (fileName.equals(childNode.getAttributes()
								.getNamedItem("name").getNodeValue())) {
							forwardUrl = childNode.getChildNodes().item(0)
									.getNodeValue();
							if(childNode.getAttributes().getNamedItem("anonymous")!=null){
								if("false".equals(childNode.getAttributes().getNamedItem("anonymous").getNodeValue())){
									anonymous = false;
								}else if("true".equals(childNode.getAttributes().getNamedItem("anonymous").getNodeValue())){
									anonymous = true;
								}
							}
						} else if ("default".equals(childNode.getAttributes()
								.getNamedItem("name").getNodeValue())) {
							defaultUrl = childNode.getChildNodes().item(0)
									.getNodeValue();
							if(childNode.getAttributes().getNamedItem("anonymous")!=null){
								if("false".equals(childNode.getAttributes().getNamedItem("anonymous").getNodeValue())){
									defaultAnonymous = false;
								}else if("true".equals(childNode.getAttributes().getNamedItem("anonymous").getNodeValue())){
									defaultAnonymous = true;
								}
							}
						} else if("*".equals(childNode.getAttributes()
								.getNamedItem("name").getNodeValue())) {
							anyUrl = childNode.getChildNodes().item(0)
									.getNodeValue();
							if(childNode.getAttributes().getNamedItem("anonymous")!=null){
								if("false".equals(childNode.getAttributes().getNamedItem("anonymous").getNodeValue())){
									anyAnonymous = false;
								}else if("true".equals(childNode.getAttributes().getNamedItem("anonymous").getNodeValue())){
									anyAnonymous = true;
								}
							}
						}

					}
				}
				System.out.println(this.getClass().getName() + "：Line " + new Throwable().getStackTrace()[0].getLineNumber()+ "\t" + "anonymous" + "\t"  + anonymous);
				System.out.println(this.getClass().getName() + "：Line " + new Throwable().getStackTrace()[0].getLineNumber()+ "\t" + "fileName" + "\t"  + fileName);
				System.out.println(this.getClass().getName() + "：Line " + new Throwable().getStackTrace()[0].getLineNumber()+ "\t" + "forwardUrl" + "\t"  + forwardUrl);
				System.out.println(this.getClass().getName() + "：Line " + new Throwable().getStackTrace()[0].getLineNumber()+ "\t" + "defaultUrl" + "\t"  + defaultUrl);
				System.out.println(this.getClass().getName() + "：Line " + new Throwable().getStackTrace()[0].getLineNumber()+ "\t" + "anyUrl" + "\t"  + anyUrl);
				if ("".equals(forwardUrl) && !"".equals(anyUrl)) {
					forwardUrl = anyUrl.replace("*", fileName);
//					if(!new File(contextPath + forwardUrl).exists()){
//						forwardUrl = "";
//					}
					if(!"".equals(forwardUrl)){
						anonymous = anyAnonymous;
					}
				}
				if ("".equals(forwardUrl) && !"".equals(defaultUrl)) {
					forwardUrl = defaultUrl;
					if(!"".equals(forwardUrl)){
						anonymous = defaultAnonymous;
					}
				}
				if ("".equals(forwardUrl)) {
					// forwardUrl为空
					filterChain.doFilter(request, response);
					return;
				}
				/** 跳转前判断是否登录，如果否则返回到登录页面 * */
				if(!anonymous){
					String loginUrl = "";
					String []sessionNames = {};
					String fromUrlKey = "";
					if(doc.getElementsByTagName("login")!=null){
						Node loginNode = doc.getElementsByTagName("login").item(0);
						if(loginNode.getChildNodes()!=null){
							for (int i = 0; i < loginNode.getChildNodes()
									.getLength(); i++) {
								if (loginNode.getChildNodes().item(i)
										.hasChildNodes()) {
									if ("url".equals(loginNode.getChildNodes()
											.item(i).getNodeName())) {
										loginUrl = loginNode.getChildNodes()
												.item(i).getChildNodes()
												.item(0).getNodeValue();
									}
									if ("session".equals(loginNode
											.getChildNodes().item(i)
											.getNodeName())) {
										sessionNames = loginNode
												.getChildNodes().item(i)
												.getChildNodes().item(0)
												.getNodeValue().split(",");
									}
									if ("fromUrlKey".equals(loginNode
											.getChildNodes().item(i)
											.getNodeName())) {
										fromUrlKey = loginNode.getChildNodes()
												.item(i).getChildNodes()
												.item(0).getNodeValue();
									}
								}
							}
						}
					}
					System.out.println(this.getClass().getName() + "：Line " + new Throwable().getStackTrace()[0].getLineNumber()+ "\t" + "loginUrl" + "\t"  + loginUrl);
					System.out.println(this.getClass().getName() + "：Line " + new Throwable().getStackTrace()[0].getLineNumber()+ "\t" + "fromUrlKey" + "\t"  + fromUrlKey);
					for(int i=0;i<sessionNames.length;i++){
						if(request.getSession().getAttribute(sessionNames[i]) == null){
							if(!"".equals(loginUrl)){
								if("".equals(fromUrlKey)){
									fromUrlKey = "fromUrl";
								}
								loginUrl = basePath + loginUrl + "?" + fromUrlKey + "=";
								response.getWriter().print("<script>location.href='" + loginUrl + "' + encodeURIComponent(location.href);</script>");
							}else{
								response.getWriter().print("There are some wrong appear in path.xml. Server can't find the value \"login>url\", please check it and try again.");
							}
							return;
						}
					}
				}
				/** 跳转 （forwardUrl不为空）* */
				ServletContext sc = getServletContext();
				RequestDispatcher rd = null;
				rd = sc.getRequestDispatcher(forwardUrl); // 定向的页面
				rd.forward(request, response);
				
			} else {
				filterChain.doFilter(request, response);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void destroy() {

	}

	public ServletContext getServletContext() {
		return filterConfig.getServletContext();
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}

	public static void main(String args[]) {
		String str="aaadadsaa_ddd";

		
		String regEx="dd"; //表示a或f

		Pattern p=Pattern.compile(regEx);

		Matcher m=p.matcher(str);

		boolean rs=m.find();
		
		System.out.println(rs);
	}
}
